import store from 'store'
import { router } from '@/main.js'
import { getToken } from '@/utils/store.js'

// 引入公共路由及权限路由
import { constRoutes, asyncRoutes } from '@/router/index'

export default {
  namespaced: true,
  state: {
    tokenInfo: getToken() || null,
    permission_routes: [],
    sidebar: {
      opened: store.get('sidebarStatus') ? !!+store.get('sidebarStatus') : true,
    },
    routes: constRoutes,
  },
  mutations: {
    TOGGLE_SIDEBAR: state => {
      state.sidebar.opened = !state.sidebar.opened
      if (state.sidebar.opened) {
        store.set('sidebarStatus', 1)
      } else {
        store.set('sidebarStatus', 0)
      }
    },
    CLOSE_SIDEBAR: state => {
      store.set('sidebarStatus', 0)
      state.sidebar.opened = false
    },
    UPDATE_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ROUTERS: (state, routes) => {
      state.permission_routes = constRoutes.concat(routes)
    },
  },
  actions: {
    toggleSideBar({ commit }) {
      commit('TOGGLE_SIDEBAR')
    },
    closeSideBar({ commit }) {
      commit('CLOSE_SIDEBAR')
    },
    /**
     * 更新用户权限，同时更新关联的权限路由
     * @param {*} param0
     * @param {Array<String>} roles 新的用户权限列表
     */
    updateRoles({ commit }, roles) {
      let accessedRoutes = []
      if (process.env.NODE_ENV === 'development') {
        accessedRoutes = asyncRoutes
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('UPDATE_ROLES', roles)
      commit('SET_ROUTERS', accessedRoutes)
      router && router.addRoutes(accessedRoutes)
    },
    setRouters({ commit }, routes) {
      commit('SET_ROUTERS', routes)
    },
  },
}

/**
 * 过滤权限路由
 * @param {Array<{}>} routes 权限路由列表
 * @param {Array<String>} roles 用户权限列表
 */

function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

/**
 * 判断路由是否有权限
 * @param {Array<String>} roles 用户权限表
 * @param {{}} route 单个路由信息
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}
